/**
 * 小程序和文档管理关联处理（1：关联，-1：取消关联）
 */
'use strict';
const encryptPassword = require('encrypt-password');
const db = uniCloud.database()
exports.main = async (event, context) => {
	let {
		password,
		email,
		userID
	} = event;
	//验证该账户是否存在
	let userInDB = await db.collection('users').where({
		email,
		password: encryptPassword(password)
	}).get()
	if (userInDB.data && userInDB.data.length === 0) {
		return {
			status: -1,
			msg: "邮箱或密码错误"
		}
	}

	// 验证是否已经关联该邮箱账号
	let chechIsRelevance = await db.collection('users').where({
		email,
		password: encryptPassword(password),
		relevanceUserID: userID
	}).get()
	if (chechIsRelevance.data && chechIsRelevance.data.length > 0) {
		return {
			status: -1,
			msg: "您已经关联该账号，请确认是否关联其他账号"
		}
	}
	//确认关联
	let relevanceResult = await db.collection('users').where({
		email,
		password: encryptPassword(password)
	}).update({
		relevanceUserID: userID
	})
	if(relevanceResult.affectedDocs !== 0){
		return {
			status:0,
			msg:"关联成功"
		}
	}

	return {
		status: -1,
		msg: "稍后重试"
	}
};
